package com.ofhb.webapp.server.utils;

import java.lang.reflect.Field;

import org.apache.commons.beanutils.PropertyUtils;

public class OfhbUtils {
	
	public static <T> T copyClass(T src, T dest) {

		Field[] destFields = dest.getClass().getDeclaredFields();
		Field[] srcFields = src.getClass().getDeclaredFields();
		int len = (destFields.length < srcFields.length) ? destFields.length : srcFields.length;
		
		for (int i = 0; i < len; i++) {
			Field srcField = srcFields[i];

			if(srcField.getName().startsWith("_") || srcField.getName().equalsIgnoreCase("serialVersionUID"))
				return src;
			
			Field destField = destFields[i];
			Object valueSrc;
			
			try {
				valueSrc = PropertyUtils.getProperty(src, srcField.getName());
				if(valueSrc != null) {
					if (srcField.getType().getName().toLowerCase().contains("dto") || srcField.getType().getName().toLowerCase().contains("entities")) {
						Object destObj = Class.forName(destField.getType().getName(), true, destField.getType().getClassLoader()).newInstance();
						OfhbUtils.copyClass(valueSrc, destObj);
						PropertyUtils.setProperty(dest, destField.getName(), destObj);
					} else {
						PropertyUtils.setProperty(dest, destField.getName(), valueSrc);
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return src;
	}

	public static <T> T printClassValues(T src) {

		Field[] srcFields = src.getClass().getDeclaredFields();
		
		Object valueSrc;
		for (int i = 0; i < srcFields.length; i++) {
			Field srcField = srcFields[i];
			if(srcField.getName().startsWith("_") || srcField.getName().equalsIgnoreCase("serialVersionUID"))
				return src;
			try {
				valueSrc = PropertyUtils.getProperty(src, srcField.getName());

				if (valueSrc != null) {
					System.out.println(src.getClass().getCanonicalName() + "." + srcField.getName() + "() => " + valueSrc.toString());
					if (srcField.getType().getName().contains("dto") || srcField.getType().getName().contains("entities")) {
						OfhbUtils.printClassValues(valueSrc);
					}
				} else {
					System.out.println(src.getClass().getCanonicalName() + "." + srcField.getName() + "() => NULL");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return src;
	}
}
